package com.skiving.cloud.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.skiving.cloud.admin.entity.SysLog;
import com.skiving.cloud.admin.entity.SysUser;
import com.skiving.cloud.admin.mapper.SysLogMapper;
import com.skiving.cloud.admin.service.SysLogService;
import com.skiving.cloud.common.utils.PageParameter;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@Component
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {

    @Override
    public Page<SysLog> queryByPage(PageParameter<Map<String, Object>> parameter){
        Page<SysLog> page = new Page<>(parameter.getPage(), parameter.getPageSize());
        Map<String, Object> param = parameter.getParam();
        QueryWrapper queryWrapper = QueryWrapper.create().from(SysLog.class)
                .as("slog").leftJoin(SysUser.class).as("usr").on(
                        wrapper -> wrapper.where(SysLog::getUserId).eq(SysUser::getId)
                );
        if(param.containsKey("staff_name") && Utils.isNotBlank(param.get("staff_name") == null ? null : param.get("staff_name").toString())){
            queryWrapper.like("usr.staff_name", param.get("staff_name").toString());
        }
        if(param.containsKey("username") && Utils.isNotBlank(param.get("username") == null ? null : param.get("username").toString())){
            queryWrapper.like("usr.username", param.get("username").toString());
        }
        if(param.containsKey("oper_time_start") && Utils.isNotBlank(param.get("oper_time_start") == null ? null : param.get("oper_time_start").toString())){
            queryWrapper.and(SysLog::getOperTime).ge(LocalDate.parse(param.get("oper_time_start").toString(), DateTimeFormatter.ISO_DATE).atStartOfDay());
        }
        if(param.containsKey("oper_time_end") && Utils.isNotBlank(param.get("oper_time_end") == null ? null : param.get("oper_time_end").toString())){
            queryWrapper.and(SysLog::getOperTime).le(LocalDate.parse(param.get("oper_time_end").toString(), DateTimeFormatter.ISO_DATE).atStartOfDay().plusDays(1));
        }
        queryWrapper.orderBy(SysLog::getOperTime).desc();
        return this.page(page, queryWrapper);
    }
}
